//
//  NSString+MKUI.m
//  MKUI
//
//  Created by 苏尚进 on 2020/10/12.
//  Copyright © 2020 moon. All rights reserved.
//

#import "NSString+MKUI.h"

@implementation NSString (MKUI)

- (NSNumber *)mk_numberValue{
    NSNumber *number;
    number = [self mk_numberOfInteger];
    if(number==nil){
        number = [self mk_numberOfLongLong];
    }
    if(number==nil){
        number = [self mk_numberOfCGFloat];
    }
    return number;
}
- (NSNumber *)mk_numberOfInteger{
    NSScanner *scanner = [[NSScanner alloc] initWithString:self];
    NSInteger value;
    if([scanner scanInteger:&value]&&scanner.isAtEnd){
        return @(value);
    }
    return nil;
}
- (NSNumber *)mk_numberOfLongLong{
    NSScanner *scanner = [[NSScanner alloc] initWithString:self];
    long long value;
    if([scanner scanLongLong:&value]&&scanner.isAtEnd){
        return @(value);
    }
    return nil;
}
- (NSNumber *)mk_numberOfCGFloat{
#if defined(__LP64__) && __LP64__
    return [self mk_numberOfDouble];
#else
    return [self mk_numberOfFloat];
#endif
}
- (NSNumber *)mk_numberOfFloat{
    NSScanner *scanner = [[NSScanner alloc] initWithString:self];
    float value;
    if([scanner scanFloat:&value]&&scanner.isAtEnd){
        return @(value);
    }
    return nil;
}
- (NSNumber *)mk_numberOfDouble{
    NSScanner *scanner = [[NSScanner alloc] initWithString:self];
    double value;
    if([scanner scanDouble:&value]&&scanner.isAtEnd){
        return @(value);
    }
    return nil;
}

- (id)mk_jsonValue{
    if(self.length==0)return nil;
    NSError *error = nil;
    id obj =[NSJSONSerialization JSONObjectWithData:[self dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&error];
    if (obj==nil&&error!=nil) {
#ifdef DEBUG
        NSLog(@"jsonValue:%@ error:%@",self,error);
#endif
    }
    return obj;
}
- (NSDictionary *)mk_jsonDictionary{
    id obj = [self mk_jsonValue];
    if ([obj isKindOfClass:[NSDictionary class]]) {
        return obj;
    }else{
        return nil;
    }
}
- (NSArray *)mk_jsonArray{
    id obj = [self mk_jsonValue];
    if ([obj isKindOfClass:[NSArray class]]) {
        return obj;
    }else{
        return nil;
    }
}
@end
